package com.icare.common.service.autoconfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 *    author  : tianhaibo
 *    email   : tianhaibo@jshuii.com
 *    time    : 2020/5/12   9:07
 *    desc    :
 *    version : v1.0
 * </pre>
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Autowired
    private ExecutorService executorService;

    @Bean
    public ExecutorService initExecutor(){
        ExecutorService threadPool = Executors.newFixedThreadPool(1);
        return threadPool;
    }

    @PreDestroy
    public void destory(){
        log.info("开始关闭线程池");
        executorService.shutdown();
        try {
            if(executorService.awaitTermination(30, TimeUnit.SECONDS)){
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            log.error("关闭线程池异常",e);
            executorService.shutdownNow();
        }
    }
}
